//basic javascript functions library
humane.error = humane.spawn({ addnCls: 'humane-libnotify-error', timeout: 1000 })



var maze_width = 5;
var maze_height = 5;
var images = new Array();

var imgs_loaded = 0;
var imgs_to_load = 0;


function load_image( url, callback )
{
	i = new Image();
	i.src = url;
	i.onload = callback;
	return i;
}


function load_tiles( callback ) {
	var filenames = ["0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010","1011","1100","1101","1110","1111"];
	var requested = filenames.length;
	var loaded = 0;
	//alert("loading "+requested);
	for( var i in filenames ) {
		var filen = filenames[i];
		i = "MapTiles2/"+filen;
		//load_script( url, function(){loaded+=1;alert("loaded "+loaded+" of "+requested);} );
		images[i] = load_image( "imgs/"+i+".png", function(){loaded+=1;} );
		//alert("loading url "+url);
	}
	wait_for_timeout( function(){return loaded>=requested;}, 1000, callback );
}


function load_crew_sprites(callback)
{
	var filenames = ["janitor","cook","captain","engineer","medic","navigator","security","pilot","security"];
	var requested = filenames.length;
	var loaded = 0;
	//alert("loading "+requested);
	for( var i in filenames ) {
		var filen = filenames[i];
		i = filen;
		//load_script( url, function(){loaded+=1;alert("loaded "+loaded+" of "+requested);} );
		images[i] = load_image( "imgs/"+i+".png", function(){loaded+=1;} );
		//alert("loading url "+url);
	}

	wait_for_timeout( function(){return loaded>=requested;}, 1000, callback );
}





function scale(x,range)
{
	//our coordinate system by default it
	//0.0-100.0
	//this translates it to the actual size of the 
	//canvas

	//abstracted for later fiddling

	var y = (x/100.0)*range;
	return y;
}


function unscale(x,range)
{
	//x is the input value
	//range is the maxium for that value (often canvas.height or canvas.width)
	return x*100.0/range;

}


function resize_canvas( nothal, margin ){
	if( 'undefined' == typeof margin ) { margin = 0; } //pixels
	var old_width = nothal.canvas.width;
	var old_height = nothal.canvas.height;
	nothal.canvas.width=0; nothal.canvas.height=0; //avoid feedback in container sizing
	var width = nothal.map.offsetWidth-2*margin;
	var height = nothal.map.offsetHeight-2*margin;
	//humane.log( "map size from ("+old_width+","+old_height+") to ("+width+","+height+")" );
	if( nothal.canvas.width != width ) {
		nothal.canvas.width = width;
	}
	if( nothal.canvas.height != height ) {
		nothal.canvas.height = height;
	}
}


// All spaces on the grid start off unconnected
// We establish a connection between 
// some origin space and an adjacent destination
// How the two are adjacent is based off of dir
function addcon(origin,dest,dir)
{
	//each location is stored as 8 bits
	//bit 3 is north cmp=8
	//bit 2 is east  cmp=4
	//bit 1 is south cmp=2
	//bit 0 is west  cmp=1
	//so to go in the desired direction
	//binary or in direction you want to go. 

	old1 = origin;
	old2 = dest;
	

	if(dir==0)	
	{
		origin.west = true;
		dest.east = true;
	}
	if(dir==1)	
	{
			origin.south = true;
			dest.north=true;
	}
	if(dir==2)	
	{
		origin.east = true;
		dest.west = true;
	}
	if(dir==3)	
	{
			origin.north = true;
			dest.south = true;
	}

}


function get_in_dir(x,y,dir) 
{
	if(dir==0)
	{
		x-=1;
	}
	if(dir==1)
	{
		y+=1;
	}
	if(dir==2)
	{
		x+=1
	}
	if(dir==3)
	{
		y-=1
	}
	//////////alert( [x,y]);
	return [x,y];
}


function drunkwalk(maze,x,y)
{
	var found = false;
	while(!found)
	{
		dir =  Math.floor((Math.random()*4)+0);
		while((dir==0&&x==0)||(dir==1&&y==maze_height-1)||(dir==2&&x==maze_width-1)||(dir==3&&y==0))
		{
			dir =  Math.floor((Math.random()*4)+0);
		}


		current = [x,y];
		next = get_in_dir(x,y,dir);
		//////////////alert(next);
		if(maze[next[0]][next[1]].inital)
		{
			found = true;
		}
		addcon(maze[x][y],maze[next[0]][next[1]],dir);
		////////////alert([x,y,next[0],next[1],dir])
		x = next[0];
		y = next[1];
	}
}





function is_room_passable(roomx,roomy,thisroom)
{
	//roomx and roomy are in 0-7 internal room choordiants
	//needs modifying for if we add more obsticles to rooms
	if(roomx>0&&roomx<7&&roomy>0&&roomy<7)
	{
		//middle of the room
		//you are currently in the clear here
		return true;
	}
	if((roomx==3||roomx==4)&&roomy==0)
	{
		return thisroom.north;
	}
	if((roomx==3||roomx==4)&&roomy==7)
	{
		return thisroom.south;
	}
	if((roomy==3||roomy==4)&&roomx==0)
	{
		return thisroom.west;
	}
	if((roomy==3||roomy==4)&&roomx==7)
	{
		return thisroom.east;
	}
	//alert([roomx,roomy]);
	return false;//you have to mess up to get here	


}

function is_passable(nothal,x,y)//internal x and y
{
	var myroomloc = get_my_room(x,y,nothal.rooms);
	var myroom = nothal.rooms[myroomloc[0]][myroomloc[1]];
	var room_width = 100.0/nothal.rooms.length;
	var room_height = 100.0/nothal.rooms[0].length;
	var roomx = Math.floor(((x-room_width*myroomloc[0])*8)/room_width);
	var roomy = Math.floor(((y-room_height*myroomloc[1])*8)/room_height);
	return is_room_passable(roomx,roomy,myroom);

}


function genmaze(width,height)
{
	//console.log("genmaze");
	maze_width = width;
	maze_height = height;

	var rooms = new Array(width);	
	for (var i = 0; i < width; i++) {
	    rooms[i] = new Array(height);
	    for (var j = 0; j < height; j++) {
	        r = new Object();
	        r.north = false;
	        r.east = false;
	        r.south = false;
	        r.west = false;
	        r.inital = false;
	        r.x = i;
	        r.y = j;
	        r.paths = new Array();
	        rooms[i][j]=r;
	    }
	}
	////////////alert(rooms);
	
	//origin is 0,0

	var startx = width-1;//Math.floor((Math.random()*width-1)+1);
	var starty = height-1;//Math.floor((Math.random()*height-1)+1);

	var currx = startx;
	var curry = starty;
	

	while(currx>0 && curry>0 )
	{
		dir = 3;
		if(currx>=curry)
		{
			dir = 0;
		}
		var get_next = get_in_dir(currx,curry,dir);
		var nextx = get_next[0];
		var nexty = get_next[1];
		//////////////alert(rooms);
		origin = rooms[currx][curry];
		origin.inital = true;
		dest = rooms[nextx][nexty];

		//////////alert([origin,dest,dir]);
		addcon(origin,dest,dir);

		currx = nextx;
		curry = nexty;
	}
	
	for (var i = 0; i < width; i++) {
	    for (var j = 0; j < height; j++) {
	    	if(!rooms[i][j].north&&!rooms[i][j].south&&!rooms[i][j].east&&!rooms[i][j].west)
	    	{
	    		drunkwalk(rooms,i,j)
	    	}
	    }
	}
	
	//console.log("generated maze");
	return rooms;
}

function draw_sprite(s,canvas,x,y,w,h)
//draw_sprite =( function (s,c,x,y,w,h)
{
	var ctx=canvas.getContext("2d");
	////////alert(s);
	ctx.drawImage(s,scale(x,canvas.width),scale(y,canvas.height),scale(w,canvas.width),scale(h,canvas.height));
//})
}

function getfilename(obj)
{
	var num=0;
	if(obj.north)
	{
		num+=8;
	}
	if(obj.east)
	{
		num+=4;
	}
	if(obj.south)
	{
		num+=2;
	}
	if(obj.west)
	{
		num+=1;
	}


	var output = ""
	for(var i=0;i<4;i++)
	{
		if(num%2==0)
		{
			output = "0"+output;
		}
		else
		{
			output = "1"+output;
		}
		num=Math.floor(num/2);
	}
	return output;
}





function render_maze(nothal)
{
	//console.log(nothal.rooms);
	var maze = nothal.rooms;
	var canvas = nothal.canvas;
	var maze_width = nothal.width;
	var maze_height = nothal.height;
	x_scale = 100.0/maze_width;
	y_scale = 100.0/maze_height;
	for (var i = 0; i < maze_width; i++) {
	    for (var j = 0; j < maze_height; j++) {
	    	var s = getfilename(maze[i][j]);
	        var room = images["MapTiles2/"+s];
	        //////alert(room);
	        draw_sprite(room,canvas,i*x_scale,j*y_scale,x_scale,y_scale);
	    }
	}
}





